package org.oos.model;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.oos.OOS4Java;
import org.oos.atom.elements.ActivityObject;
import org.oos.atom.elements.Author;
import org.oos.atom.elements.Link;
import org.oos.atom.elements.Text;
import org.oos.atom.entries.ActivityEntry;
import org.oos.model.UserAvatar.AvatarSize;

public class Activity extends AbstractEntityImpl {
	private static final long serialVersionUID = 7903836753508565394L;

	private ActivityEntry entry;
	private Action action;
	private ObjectType objectType;
	private String mainUrl;
	private String captionUrl;

	public Activity(OOS4Java oos4Java, ActivityEntry entry) {
		super(oos4Java);
		this.entry = entry;
	}

	public Action getAction() {
		if (action == null && entry.getVerb() != null) {
			action = Action.resolve(entry.getVerb());
		}
		return action;
	}

	public ObjectType getObjectType() {
		if (objectType == null) {
			objectType = ObjectType.resolve(entry.getObject().getObjectType());
		}
		return objectType;
	}

	public Author getAuthor() {
		return entry.getActor();
	}

	public ActivityObject getActivityObject() {
		return entry.getObject();
	}

	public String getDescription() {
		return entry.getTitle().getValue();
	}

	public String getMainUrl() {
		if (mainUrl == null) {
			mainUrl = Link.find(entry.getObject().getLinks(), "alternate").get(
					0).getHref();
		}
		return mainUrl;
	}

	public String getCaptionurl() {
		if (captionUrl == null) {
			switch (getObjectType()) {
			case PERSON:
				captionUrl = entry.getObject().getAvatar().getImagePath(
						AvatarSize.XLARGE);
				break;
			case PICTURE:
			case VIDEO:
				captionUrl = Link.find(entry.getObject().getLinks(), "media")
						.get(0).getHref();
				break;
			}
		}
		return captionUrl;
	}

	public String getServiceUrl() {
		List<Link> links = Link.find(entry.getObject().getLinks(), "service");
		if (links.size() > 0) {
			return links.get(0).getHref();
		} else {
			return null;
		}
	}

	public String getSiteName() {
		Text title = entry.getTitle();
		if (title != null) {
			return title.getValue();
		}
		return null;
	}

	public enum Action {
		POST, FOLLOW, PUT, CHECKIN, COMMENT, FAVORITE;

		public static Action resolve(String name) {
			List<String> parts = new ArrayList<String>(Arrays.asList(name
					.split("/")));
			String verb = parts.get(parts.size() - 1).toUpperCase().replace(
					"-", "");
			return Action.valueOf(verb);
		}
	}

	public enum ObjectType {
		PERSON, PLACE, PICTURE, VIDEO, AREA, APP;

		public static ObjectType resolve(String name) {
			List<String> parts = new ArrayList<String>(Arrays.asList(name
					.split("/")));
			String type = parts.get(parts.size() - 1).toUpperCase();
			return ObjectType.valueOf(type);
		}
	}

	public Date getDate() {
		if (entry != null) {
			return entry.getUpdated();
		}
		return null;
	}

	public String getObjectSlug() {
		return entry.getObject().getSlug();
	}

}
